import subprocess
import sys
import thread
import time

class FlushFile(object): 
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()

def Execute_File():
    global popen
    sys.stdout = FlushFile(sys.__stdout__)
    popen = subprocess.Popen(['./client.sh'], stdin=subprocess.PIPE,stdout = subprocess.PIPE)

def receive_thread():
    global mylist
    count=0
    mylist=[]
    while True:
        next_line = popen.stdout.readline().strip()
        parts=next_line.split('&&')
        if parts[0]=="$$LIST":
            length=len(parts)
            mylist=[]
            for i in range(1,length):
                mylist.append(parts[i])
        elif parts[0]=="$$MSSG":
            count+=1
#         print count
        time.sleep(0.5)

def send_thread():
    total=10
    while total>-1:
        popen.stdin.write("$$REQUEST" +'\n')
        for active in mylist:
            popen.stdin.write("$$MSSG" + "&&" +active+ "&&" +"hello"+'\n')
            print "total:",total
            time.sleep(0.5)
            total-=1
            if total<0:
                break

Execute_File()
thread.start_new_thread(receive_thread, ()) # create thread for receiving stdout from subprocess
time.sleep(1)
thread.start_new_thread(send_thread, ())

while True:
    pass

